package es.juanc.threads.concurrent;

import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchExecutor {

	public static void main(String args[]) {

		CountDownLatch cdl = new CountDownLatch(5);
		CountDownLatch cdl2 = new CountDownLatch(5);
		CountDownLatch cdl3 = new CountDownLatch(5);
		CountDownLatch cdl4 = new CountDownLatch(5);

		ExecutorService es = Executors.newFixedThreadPool(3);

		es.execute(new ThreadWorker(cdl, "A"));
		es.execute(new ThreadWorker(cdl2, "B"));
		es.execute(new ThreadWorker(cdl3, "C"));
		es.execute(new ThreadWorker(cdl4, "D"));

		try {
			cdl.await();
			cdl2.await();
			cdl3.await();
			cdl4.await();
		} catch (InterruptedException exc) {
			System.out.println(exc);
		}

		es.shutdown();
	}
}

class ThreadWorker implements Runnable {

	String name;
	CountDownLatch latch;

	public ThreadWorker(CountDownLatch c, String n) {
		latch = c;
		name = n;
		//new Thread(this);
	}

	public void run() {
		System.out.println( name + " " + new Date() );
		for (int i = 0; i < 5; i++) {
			latch.countDown();
			System.out.println( latch.getCount() );
		}
		System.out.println( "... " + name + " " + new Date() );
	}
}
